package com.swg.seckill.service.impl;

import com.swg.seckill.exception.GlobalException;
import com.swg.seckill.pojo.User;
import com.swg.seckill.mapper.UserMapper;
import com.swg.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swg.seckill.utils.CookieUtil;
import com.swg.seckill.utils.MD5Util;
import com.swg.seckill.utils.UUIDUtil;
import com.swg.seckill.utils.vo.LoginVo;
import com.swg.seckill.utils.vo.RespBean;
import com.swg.seckill.utils.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author swg
 * @since 2021-11-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    @Qualifier("myRedisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public RespBean login(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {

        User user = userMapper.selectById(loginVo.getMobile());

        if(user == null){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //判断密码是否正确
        if(!MD5Util.formPassToDBPass(loginVo.getPassword(),user.getSlat()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //生成cookie
        String ticket = UUIDUtil.uuid();
//        request.getSession().setAttribute(ticket,user);
        redisTemplate.opsForValue().set("user" + ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        return RespBean.success(user);
    }

    @Override
    public User getUserByCookie(String userTicket) {
        if(userTicket == null){
            return null;
        }

        User user = (User) redisTemplate.opsForValue().get("user" + userTicket);

        return user;
    }
}
